package com.kqb.sgadmin.facade;

import cn.hutool.core.bean.BeanUtil;
import com.kqb.sgadmin.model.Admin;
import com.kqb.sgadmin.model.dto.admin.AdminUpdateDTO;
import com.kqb.sgadmin.model.vo.AdminVO;
import com.kqb.sgadmin.service.AdminRoleService;
import com.kqb.sgadmin.service.AdminService;
import com.kqb.sgadmin.service.pipeline.create.AdminCreateHandler;
import com.kqb.sgadmin.service.pipeline.create.context.AdminCreateContext;
import com.kqb.sgcommon.base.exception.BusinessException;
import com.kqb.sgcommon.base.utils.ThrowUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * @author D
 */
@Service
public class AdminFacadeService {

    @Resource
    private List<AdminCreateHandler> createHandlers;

    @Resource
    private AdminService adminService;

    @Resource
    private AdminRoleService adminRoleService;


    /**
     * 添加管理员
     *
     * @param adminCreateContext
     */
    public void add(AdminCreateContext adminCreateContext) {
        createHandlers.forEach(handler -> handler.handle(adminCreateContext));
    }

    @Transactional
    public void updateAdmin(AdminUpdateDTO adminUpdateDTO) {
        Admin oldAdmin = adminService.getById(adminUpdateDTO.getAid());
        if (oldAdmin == null) {
            BusinessException.of("用户不存在");
        }
        String phone = adminUpdateDTO.getPhone();
        String username = adminUpdateDTO.getUsername();
        // 如果用户名和手机号都未被修改，则不需要验证唯一性
        if (!username.equals(oldAdmin.getUsername()) && !phone.equals(oldAdmin.getPhone())) {
            ThrowUtils.throwIf(adminService.isExist(username, phone), BusinessException.of("用户名或手机号已被占用"));
        }
        Admin admin = BeanUtil.toBean(adminUpdateDTO, Admin.class);
        admin.setId(adminUpdateDTO.getAid());
        boolean b = adminService.updateById(admin);
        ThrowUtils.throwNotIf(b, BusinessException.of("更新管理员失败"));
        Integer aid = admin.getId();
        List<Integer> roleIds = adminUpdateDTO.getRoleIds();
        if (roleIds != null) {
            adminRoleService.batchInsertRoles(aid, roleIds);
        }
    }

    public AdminVO getAllInfoByAdminId(Integer loginId) {
        Admin admin = adminService.getBaseMapper().selectById(loginId);

        return BeanUtil.toBean(admin, AdminVO.class);

    }
}
